/**
 * Game.js 进行游戏的配置
 * 1. 创建游戏画面
 * 2. 控制蛇的逻辑
 */

var mapRow = 20;
var mapCol = 20;

function Game() {
  // 行数
  this.row = mapRow;
  // 列数
  this.col = mapCol;
  // 分数
  this.score = 0;

  // 初始化地图
  this.init();
  // 创建蛇
  this.snake = new Snake(this);
  // 创建食物
  this.food = new Food(this);

  this.bindEvent();
}

// 创建地图
Game.prototype.init = function () {
  this.map = document.createElement('table');
  for (let i = 0; i < this.row; i++) {
    let tr = document.createElement('tr');
    for (let j = 0; j < this.col; j++) {
      let td = document.createElement('td');
      tr.appendChild(td);
    }
    this.map.appendChild(tr);
  }
  document.getElementById('game').appendChild(this.map);
};

// 渲染图片
Game.prototype.setHTML = function (row, col, html, className) {
  if (html != '') {
    this.map.getElementsByTagName('tr')[row].getElementsByTagName('td')[
      col
    ].innerHTML = `<img src='${html}' class='${className}'>`;
  } else {
    this.map.getElementsByTagName('tr')[row].getElementsByTagName('td')[
      col
    ].innerHTML = '';
  }
};

// 清除地图
Game.prototype.clean = function () {
  for (let i = 0; i < this.row; i++) {
    for (let j = 0; j < this.col; j++) {
      this.setHTML(i, j, '');
    }
  }
};

// 事件监听
Game.prototype.bindEvent = function () {
  var self = this;
  document.addEventListener('keydown', function (e) {
    switch (e.keyCode) {
      case 38:
      case 87: // 'N'
        self.snake.changeDirection(0);
        break;
      case 65:
      case 37: // 'E'
        self.snake.changeDirection(3);
        break;
      case 83:
      case 40: // 'S'
        self.snake.changeDirection(2);
        break;
      case 68:
      case 39: // 'W'
        self.snake.changeDirection(1);
      default:
        break;
    }
    // console.log(self.snake);
  });
  document.getElementById('restart').addEventListener('click', function () {
    self.restart();
  });
  document.getElementById('startGame').addEventListener('click', function () {
    self.start();
  });
};

Game.prototype.start = function () {
  this.frame = 0;
  const startView = document.getElementById('start');
  startView.style.display = 'none';
  this.timer = setInterval(() => {
    game.frame++;
    game.clean();

    // 显示分数
    document.getElementById('score').innerHTML = '分数: ' + game.score;

    // 控制蛇的速度，蛇的长度越长，速度越快
    const duration =
      game.snake.body.length < 30 ? 30 - game.snake.body.length : 3;

    game.frame % duration == 0 && game.snake.update();
    if (!this.timer) return;
    game.snake.render();
    game.food.render();
  }, 10);
};

Game.prototype.restart = function () {
  location.reload();
};

Game.prototype.gameOver = function () {
  const over = document.getElementById('over');
  document.getElementById('final-score').innerHTML = game.score;
  over.style.display = 'block';
  clearInterval(this.timer);
  this.timer = null;
  this.frame = 0;
};
